package com.ruoyi.credit.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.credit.domain.*;
import com.ruoyi.credit.mapper.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.credit.service.IEvaTaskService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 信用评价任务计划Service业务层处理
 *
 * @author zhulei
 * @date 2022-03-10
 */
@Service
public class EvaTaskServiceImpl implements IEvaTaskService
{
    @Autowired
    private EvaTaskMapper evaTaskMapper;

    @Autowired
    private EvaTaskDeptMapper evaTaskDeptMapper;

    @Autowired
    private EvaTaskContractMapper evaTaskContractMapper;

    @Autowired
    private EvaTaskDetailMapper evaTaskDetailMapper;

    @Autowired
    private ContractPayMapper contractPayMapper;

    @Autowired
    private ContractIncomeMapper contractIncomeMapper;

    @Autowired
    private EvaTaskResultMapper evaTaskResultMapper;
    /**
     * 查询信用评价任务计划
     *
     * @param taskId 信用评价任务计划主键
     * @return 信用评价任务计划
     */
    @Override
    public EvaTask selectEvaTaskByTaskId(Long taskId)
    {
        return evaTaskMapper.selectEvaTaskByTaskId(taskId);
    }

    /**
     * 查询信用评价任务计划列表
     *
     * @param evaTask 信用评价任务计划
     * @return 信用评价任务计划
     */
    @Override
    public List<EvaTask> selectEvaTaskList(EvaTask evaTask)
    {
        return evaTaskMapper.selectEvaTaskList(evaTask);
    }

    /**
     * 新增信用评价任务计划
     *
     * @param evaTask 信用评价任务计划
     * @return 结果
     */
    @Transactional
    @Override
    public int insertEvaTask(EvaTask evaTask)
    {
        evaTask.setCreateTime(DateUtils.getNowDate());
        evaTask.setCreateBy(ShiroUtils.getLoginName());
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        evaTask.setTaskYear(String.valueOf(year));
        int ret = evaTaskMapper.insertEvaTask(evaTask);

        // 保存到任务合同信息表
        insertTaskContract(evaTask);

        // 保存到任务部门信息表
        insertTaskDept(evaTask);

        // 发布的时候，保存到任务详情表,
//        insertTaskDetail(evaTask);
        return ret;
    }

    /***
     * 新增任务合同信息表
     */
    public void insertTaskContract(EvaTask evaTask){
        List<EvaTaskContract> taskContractList = evaTask.getTaskContractList();
        Long taskId = evaTask.getTaskId();
        String contractClass = evaTask.getContractClass();
        if(taskContractList!= null && !taskContractList.isEmpty()){

            for (EvaTaskContract evaTaskContract : taskContractList) {
                evaTaskContract.setTaskId(taskId);
                evaTaskContract.setTargetType(contractClass);

                // 查询合同对应的供应商或者客户id,1代表供应商，2代表客户
                if("1".equals(contractClass)){
                    ContractPay contractSupplierInfo = contractPayMapper.getContractSupplierInfo(evaTaskContract.getContractId());
                    evaTaskContract.setTargetId(contractSupplierInfo.getTargetId());
                } else if("2".equals(contractClass)){
                    // 保存到contract_income_id 字段
                    evaTaskContract.setContractIncomeId(evaTaskContract.getContractId());
                    // 保存客户id
                    ContractIncome contractCustomerInfo = contractIncomeMapper.getContractCustomerInfo(evaTaskContract.getContractId());
                    evaTaskContract.setTargetId(contractCustomerInfo.getTargetId());
                }
            }
            evaTaskContractMapper.insertEvaTaskContractBatch(taskContractList);
        }
    }

    /***
     * 新增任务部门信息表
     */
    public void insertTaskDept(EvaTask evaTask){
        List<EvaTaskDept> taskDeptList = evaTask.getTaskDeptList();
        Long taskId = evaTask.getTaskId();
        if(taskDeptList!= null && !taskDeptList.isEmpty()){
            for (EvaTaskDept evaTaskDept : taskDeptList) {
                evaTaskDept.setTaskId(taskId);
            }
            evaTaskDeptMapper.insertEvaTaskDeptBatch(taskDeptList);
        }
    }

    /***
     * 新增任务详情表
     */
    public void insertTaskDetail(EvaTask evaTask){
        List<EvaTaskContract> taskContractList = evaTask.getTaskContractList();
        List<EvaTaskDept> taskDeptList = evaTask.getTaskDeptList();
        Long taskId = evaTask.getTaskId();
        String taskName = evaTask.getTaskName();
        String contractClass = evaTask.getContractClass();
        String contractType = evaTask.getContractType();
        String taskYear = evaTask.getTaskYear();
        ArrayList<EvaTaskDetail> evaTaskDetails = new ArrayList<>();
        if(taskContractList!= null && !taskContractList.isEmpty()){
            for (EvaTaskContract evaTaskContract : taskContractList) {

                if(taskDeptList!= null && !taskDeptList.isEmpty()){
                    for (EvaTaskDept evaTaskDept : taskDeptList) {
                        EvaTaskDetail evaTaskDetail = new EvaTaskDetail();
                        evaTaskDetail.setTaskId(taskId);
                        evaTaskDetail.setDeptId(evaTaskDept.getDeptId());
                        evaTaskDetail.setContractId(evaTaskContract.getContractId());
                        evaTaskDetail.setTargetId(evaTaskContract.getTargetId());
                        evaTaskDetail.setTargetName(evaTaskContract.getTargetName());
                        evaTaskDetail.setTaskName(taskName);
                        evaTaskDetail.setContractName(evaTaskContract.getContractName());
                        evaTaskDetail.setContractClass(contractClass);
                        evaTaskDetail.setContractType(contractType);
                        evaTaskDetail.setYear(taskYear);
                        evaTaskDetail.setWeight(evaTaskDept.getWeight());
                        evaTaskDetail.setCreateTime(DateUtils.getNowDate());
                        evaTaskDetail.setCreateBy(ShiroUtils.getLoginName());
                        evaTaskDetails.add(evaTaskDetail);
                    }
                }
            }
        }
        if(evaTaskDetails.size() > 0){
            evaTaskDetailMapper.insertEvaTaskDetailBatch(evaTaskDetails);
        }
    }

    /**
     * 修改信用评价任务计划
     *
     * @param evaTask 信用评价任务计划
     * @return 结果
     */
    @Override
    public int updateEvaTask(EvaTask evaTask)
    {
        evaTask.setUpdateTime(DateUtils.getNowDate());
        return evaTaskMapper.updateEvaTask(evaTask);
    }

    /**
     * 批量删除信用评价任务计划
     *
     * @param taskIds 需要删除的信用评价任务计划主键
     * @return 结果
     */
    @Override
    public int deleteEvaTaskByTaskIds(String taskIds)
    {
        return evaTaskMapper.deleteEvaTaskByTaskIds(Convert.toStrArray(taskIds));
    }

    /**
     * 删除信用评价任务计划信息
     *
     * @param taskId 信用评价任务计划主键
     * @return 结果
     */
    @Override
    public int deleteEvaTaskByTaskId(Long taskId)
    {
        return evaTaskMapper.deleteEvaTaskByTaskId(taskId);
    }

    /**
     * 发起评价任务
     * @param taskId
     * @return
     */
    @Override
    public int taskBegin(Long taskId) {
        // 查询任务信息
        EvaTask evaTask = evaTaskMapper.selectEvaTaskByTaskId(taskId);

        // 查询任务合同列表
        EvaTaskContract evaTaskContract = new EvaTaskContract();
        evaTaskContract.setTaskId(taskId);
        List<EvaTaskContract> evaTaskContracts = evaTaskContractMapper.selectEvaTaskContractList(evaTaskContract);

        // 查询任务部门列表
        EvaTaskDept evaTaskDept = new EvaTaskDept();
        evaTaskDept.setTaskId(taskId);
        List<EvaTaskDept> evaTaskDepts = evaTaskDeptMapper.selectEvaTaskDeptList(evaTaskDept);

        evaTask.setTaskContractList(evaTaskContracts);
        evaTask.setTaskDeptList(evaTaskDepts);
        // 生成任务详情列表
        insertTaskDetail(evaTask);

        // 修改任务状态
        EvaTask evaTask1 = new EvaTask();
        evaTask1.setTaskId(taskId);
        evaTask1.setStatus("1");
        evaTaskMapper.updateEvaTask(evaTask1);
        return 1;
    }

    /**
     * 结束评价任务
     * @param taskId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int taskEnd(Long taskId) {
        // 如果有未完成的评价，，无法结束，返回结束评价任务失败
        int ret = evaTaskDetailMapper.checkTaskEnd(taskId);
        if (ret > 0){
            return -1;
        }
        // 如果都完成了评价，修改任务评价状态为结束；
        EvaTask evaTask = new EvaTask();
        evaTask.setTaskId(taskId);
        evaTask.setStatus("2");
        evaTaskMapper.updateEvaTask(evaTask);

        // 将对应的打分记录 状态也设置为完成状态（不允许再修改打分）。同时计算权重分数
        EvaTaskDetail evaTaskDetail = new EvaTaskDetail();
        evaTaskDetail.setTaskId(taskId);
        evaTaskDetail.setStatus("2");
        evaTaskDetailMapper.updateEvaTaskDetailBatch(evaTaskDetail);

        // 评价任务确认结束后，生成评价结果（可以异步生成）
        buildTaskResult(taskId);

        return 1;
    }

    /**
     * 生成评价结果
     */
    public void buildTaskResult(Long taskId){

        // 供应商总分除以供应商合同的个数 = 供应商平均分
        List<EvaTaskDetail> evaTaskDetails = evaTaskDetailMapper.selectResultByTask(taskId);

        // 生成评价结果list
        if(evaTaskDetails != null && !evaTaskDetails.isEmpty()){
            ArrayList<EvaTaskResult> evaTaskResults = new ArrayList<>();
            for (EvaTaskDetail evaTaskDetail : evaTaskDetails) {
                EvaTaskResult evaTaskResult = new EvaTaskResult();
                evaTaskResult.setTaskId(taskId);
                evaTaskResult.setTargetId(evaTaskDetail.getTargetId());
                evaTaskResult.setTaskName(evaTaskDetail.getTaskName());
                evaTaskResult.setTargetClass(evaTaskDetail.getContractClass());
                evaTaskResult.setTargetName(evaTaskDetail.getTargetName());
                evaTaskResult.setYear(evaTaskDetail.getYear());
                // 计算平均分和评级
                BigDecimal sumScore = evaTaskDetail.getSumScore();
                BigDecimal contractNums = evaTaskDetail.getContractNums();
                BigDecimal score = sumScore.divide(contractNums, 2, BigDecimal.ROUND_HALF_UP);
                String rating = getRating(score);
                evaTaskResult.setScore(score.toString());
                evaTaskResult.setRating(rating);

                evaTaskResults.add(evaTaskResult);
            }

            if(evaTaskResults.size() > 0){
                // list保存到评价结果表
                evaTaskResultMapper.insertEvaTaskResultBatch(evaTaskResults);
            }
        }
    }

    // 计算评级 100分~90分为A级，89分~75分为B级，74分~60分为C级，59分及其以下为D级。
    public String getRating(BigDecimal score){
        if(score.compareTo(new BigDecimal(89)) > 0){
            return "A";
        } else if(score.compareTo(new BigDecimal(74)) > 0){
            return "B";
        } else if(score.compareTo(new BigDecimal(59)) > 0){
            return "C";
        } else{
            return "D";
        }
    }
}
